/**
 * 文件上传服务
 */

import { BaseApiService, API_CONFIG, AuthManager } from '../utils/api';
import { FileUploadVo } from '../types/api';

export class FileService extends BaseApiService {
  
  /**
   * 上传单个文件
   */
  async uploadFile(formData: FormData): Promise<FileUploadVo> {
    // 获取token
    const token = await AuthManager.getToken();
    console.log('文件上传使用的token:', token ? '有token' : '无token');

    // 对于文件上传，需要特殊处理headers
    const response = await fetch(`${API_CONFIG.BASE_URL}/api/file/upload`, {
      method: 'POST',
      body: formData,
      headers: {
        // 不设置Content-Type，让浏览器自动设置multipart/form-data边界
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('文件上传失败:', errorText);
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const result = await response.json();
    if (result.code === 200) {
      return result.data;
    } else {
      throw new Error(result.msg || '文件上传失败');
    }
  }

  /**
   * 上传多个文件
   */
  async uploadFiles(files: File[]): Promise<FileUploadVo[]> {
    const formData = new FormData();
    files.forEach(file => {
      formData.append('files', file);
    });

    const response = await fetch(`${this.http['baseURL']}/api/file/upload/batch`, {
      method: 'POST',
      body: formData,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('auth_token') || ''}`,
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const result = await response.json();
    if (result.code === 200) {
      return result.data;
    } else {
      throw new Error(result.msg || '文件上传失败');
    }
  }

  /**
   * 检查文件类型
   */
  async checkFileType(file: File): Promise<boolean> {
    const formData = new FormData();
    formData.append('file', file);

    const response = await fetch(`${this.http['baseURL']}/api/file/check/type`, {
      method: 'POST',
      body: formData,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('auth_token') || ''}`,
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const result = await response.json();
    if (result.code === 200) {
      return result.data;
    } else {
      throw new Error(result.msg || '文件类型检查失败');
    }
  }

  /**
   * 检查文件大小
   */
  async checkFileSize(file: File): Promise<boolean> {
    const formData = new FormData();
    formData.append('file', file);

    const response = await fetch(`${this.http['baseURL']}/api/file/check/size`, {
      method: 'POST',
      body: formData,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('auth_token') || ''}`,
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const result = await response.json();
    if (result.code === 200) {
      return result.data;
    } else {
      throw new Error(result.msg || '文件大小检查失败');
    }
  }

  /**
   * 删除文件
   */
  async deleteFile(fileId: number): Promise<boolean> {
    return this.handleResponse(
      this.http.delete<boolean>(`/api/file/${fileId}`)
    );
  }
}

// 导出单例实例
export const fileService = new FileService();
